package pers.mingshan.thread.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadDemo1 {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //1.创建Thread对象
        Thread thread1=new Thread() {
            @Override
            public void run() {
                while (true) {
                    
                    try {
                        System.out.println("1:"+Thread.currentThread().getName());
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        thread1.start();

        // 2.创建Runnable对象，并将其传给Thread对象
        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        System.out.println("2:" + Thread.currentThread().getName());
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread2.start();

        // 3. 创建FutureTask对象，创建Callable子类对象，复写call(相当于run)方法，
        // 将其传递给FutureTask对象（相当于一个Runnable）。
        // 创建Thread类对象，将FutureTask对象传递给Thread对象。
        // 调用start方法开启线程。这种方式可以获得线程执行完之后的返回值。
        FutureTask<String> ft = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("3:" + Thread.currentThread().getName());
                return "aaaa";
            }
        });

        Thread thread3 = new Thread(ft);
        thread3.start();
        // 调用这个方法会导致程序阻塞，必须等到子线程结束后才会得到返回值
        String result = ft.get();
        System.out.println("result : " + result);

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        System.out.println("3:" + Thread.currentThread().getName());
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
